import { apiRedImages, apiRedXcCode, apiShareRed } from '../../api/index'
let timer
let page = {
  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    showImg: false,
    isLoaded: false,
    goodsHeight: 0,
    index: 0,
    showTags: [],
    showTips: '',
    loads: true
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad (options) {
    let h = wx.getSystemInfoSync().screenHeight / 2
    this.screenRatio = wx.getSystemInfoSync().screenWidth / 375
    this.setData({
      hh: h,
      isIphoneX: getApp().globalData.isIphoneX,
      navHeight: getApp().globalData.navHeight
    })
    // 获取二维码信息
    apiRedXcCode().then(
      res => {
        console.log(res)
        this.eqPath = res.data
      }
    )
    this.getShareData()
    this.getImg()
    timer = setInterval(
      () => {
        this.animations()
      }, 4000)
  },
  animations () {
    this.data.index++
    if (this.data.index === this.data.showTags.length) {
      this.data.index = 0
    }
    this.setData({
      showTips: this.data.showTags[this.data.index]
    })
    this.times = setTimeout(() => {
      this.setData({
        showTips: ''
      })
    }, 3200)
  },
  getImg () {
    apiRedImages().then(
      res => {
        this.setData({
          hasImg: res.data
        })
      }
    )
  },
  // 获取红包数据统计
  getShareData () {
    apiShareRed().then(
      res => {
        this.setData({
          showData: res.data,
          showTags: res.data.invitation_member,
          loads: false
        })
        wx.stopPullDownRefresh()
      }
    )
  },
  showShare () {
    this.setData({
      show: true
    })
  },
  onClose () {
    this.setData({
      show: false
    })
  },
  cancelPop () {
    this.setData({
      show: false
    })
  },
  cleanTime () {
    clearInterval(timer)
    timer = null
    clearTimeout(this.times)
    this.times = null
    this.setData({
      show: false
    })
  },
  onHide () {
    this.cleanTime()
  },
  onUnload () {
    this.cleanTime()
  },
  // 生成图片
  creatImg () {
    this.setData({
      show: false,
      showImg: true
    })
    wx.showLoading({
      title: '拼命生成中'
    })
    wx.getImageInfo({
      src: this.data.hasImg.share_img,
      success: (res) => {
        const width = res.width / 2
        const height = res.height / 2
        this.setData({
          goodsHeight: height * this.screenRatio
        })
        const ctx = wx.createCanvasContext('myCanvas')
        // 底图
        ctx.drawImage(res.path, 0, 0, width * this.screenRatio, height * this.screenRatio)
        ctx.beginPath()
        ctx.setTextAlign('center') // 文字居中
        ctx.setFillStyle('#ffffff')
        ctx.setFontSize(14)
        ctx.fillText('长按扫码领钱', 167 * this.screenRatio, 470 * this.screenRatio)
        ctx.stroke()
        wx.getImageInfo({
          src: wx.getStorageSync('avatarUrl'),
          success: (userImg) => {
            // 绘制头像
            ctx.save()
            ctx.beginPath() // 开始绘制
            // 先画个圆   前两个参数确定了圆心 （x,y） 坐标  第三个参数是圆的半径  四参数是绘图方向
            ctx.arc(175.5 * this.screenRatio, 35.5 * this.screenRatio, 22.5 * this.screenRatio, 0, Math.PI * 2)
            ctx.clip()
            ctx.drawImage(userImg.path, 153 * this.screenRatio, 13 * this.screenRatio, 45 * this.screenRatio, 45 * this.screenRatio)
            ctx.restore()
            console.log(this.eqPath)
            wx.getImageInfo({
              src: 'https://shop.duonadian.com/upload/redpackage/redCode_74.jpg',
              success: (eq) => {
                console.log(eq)
                ctx.drawImage(eq.path, 135 * this.screenRatio, 380 * this.screenRatio, 68 * this.screenRatio, 68 * this.screenRatio)
                ctx.draw(false, (res) => {
                  if (res.errMsg.indexOf('ok') !== -1) {
                    wx.canvasToTempFilePath({
                      x: 0,
                      y: 0,
                      canvasId: 'myCanvas',
                      success: (res) => {
                        this.fileImgPath = res.tempFilePath
                        wx.hideLoading()
                        this.setData({
                          isLoaded: true,
                          canvasImg: res.tempFilePath
                        })
                      }
                    })
                  }
                })
              },
              fail: (err) => {
                console.log(err)
              }
            })
          }
        })
      }
    })
  },
  saveImage () {
    wx.saveImageToPhotosAlbum({
      filePath: this.fileImgPath,
      success: () => {
        wx.showToast({
          title: '保存成功',
          success: () => {
            this.setData({
              showImg: false
            })
          }
        })
      },
      fail: (err) => {
        if (err.errMsg === 'saveImageToPhotosAlbum:fail:auth denied' || err.errMsg === 'saveImageToPhotosAlbum:fail auth deny') {
          wx.showModal({
            title: '提示',
            content: '需要您授权保存相册',
            showCancel: false,
            success: (sure) => {
              wx.openSetting({
                success: (set) => {
                  if (set.authSetting['scope.writePhotosAlbum']) {
                    wx.showModal({
                      title: '提示',
                      content: '获取权限成功,再次点击图片即可保存',
                      showCancel: false
                    })
                  } else {
                    wx.showModal({
                      title: '提示',
                      content: '获取权限失败，将无法保存到相册哦~',
                      showCancel: false
                    })
                  }
                },
                fail: (failData) => {
                }
              })
            }
          })
        }
      }
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh () {
    this.getShareData()
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage () {
    return {
      title: '多拿点邀请您新用户注册,领现金红包！',
      imageUrl: this.data.hasImg.new_img,
      path: `/pages/shopping/shopping?source_uid=${wx.getStorageSync('uid')}`
    }
  }
}
Page(page)
